/*
 * @Descripttion: 
 * @version: 
 * @Author: ChenXiang
 * @Date: 2021-09-28 20:15:32
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-09-30 13:19:28
 */

import React, { useState, useEffect, useRef } from 'react';
import Item from "./item";
import './index.scss'
export interface dataItemProps {
  value: string,
  text: string
}
export interface ButtonGroupProps {
  data: dataItemProps[],
  value?: string[],
  defaultValue?: string | string[],
  type?: string,
  onChange?: (any) => void;
}
const ButtonGroup: React.FC<ButtonGroupProps> = (props) => {
  const [data, setData] = useState(props.data);
  const [currentValue, setCurrentValue] = useState(props.value);
  useEffect(() => {
    setData(props.data)
  }, [props.data])
  const dedupe = (array) => {
    return Array.from(new Set(array));
  }
  const isActive = (currentValue, propsValue) => {
    if (Array.isArray(propsValue)) {
      return propsValue.includes(currentValue)
    }
  }
  console.log('data', data, currentValue)
  return <div className="button-group-wrap">
    <div className="button-group">
      {data.map((item, index) => {
        return <Item
          isActive={isActive(item.value, currentValue)}
          data={item} key={item.value} index={Number(item.value)}
          onClick={(isActive, item, index) => {
            if (isActive === false) {
              const newValue: any = dedupe([...currentValue, item.value])
              setCurrentValue(newValue)
            } else {

              // currentValue.splice(index, 1);
              // setCurrentValue(currentValue)

              setCurrentValue(currentValue => {
                const newValue: any = JSON.parse(JSON.stringify(currentValue))
                console.log('currentValue', currentValue)
                console.log('index', index)

                const a = newValue.splice(index, 1)

                console.log('a', a);
                console.log('currentValue', currentValue);
                return newValue.sort()
              })
            }
          }} />
      }
      )}
    </div>
  </div>
};

export default ButtonGroup;
